package com.example.utils.mybatis;

import com.google.common.base.CaseFormat;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 扩展 Mybatis 注解，作用于 Insert 插入操作上
 */
public class SimpleInsertLanguageDriver extends XMLLanguageDriver implements LanguageDriver {

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {

        // 正则匹配
        Pattern inPattern = Pattern.compile("\\(#\\{(\\w+)\\}\\)");
        Matcher matcher = inPattern.matcher(script);
        if (matcher.find()) {
            StringBuilder builder = new StringBuilder();
            StringBuilder values = new StringBuilder();
            builder.append("(");

            for (Field field : parameterType.getDeclaredFields()) {
                // 排除被 Invisble 修饰的变量
                if (!field.isAnnotationPresent(Invisible.class)){
                    // 字段驼峰命名转换
                    builder.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName()) + ",");
                    values.append("#{" + field.getName() + "},");
                }
            }

            builder.deleteCharAt(builder.lastIndexOf(","));
            values.deleteCharAt(values.lastIndexOf(","));
            builder.append(") values (" + values.toString() + ")");

            script = matcher.replaceAll(builder.toString());
            script = "<script>" + script + "</script>";

            System.out.println("SimpleInsertLanguageDriver - 生成的SQL：" + script);
        }
        return super.createSqlSource(configuration, script, parameterType);
    }
}
